package com.broadtext.rms.system.action;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.rms.system.model.TtPackWeeklyReport;
import com.broadtext.rms.system.service.ITtPackWeeklyReportService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * <p>ClassName: WeeklyReportAction</p>
 * <p>Description: 周报控制层</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-2</p>
 */
@Controller
@RequestMapping("/main/report/weekly")
public class WeeklyReportAction {

    /**
     * 区域服务类
     */
    @Autowired
    @Qualifier("ttPackWeeklyReportService")
    private ITtPackWeeklyReportService ttPackWeeklyReportService;

    @RequestMapping(value = "/getWeeklyReport.mvc")
    @ResponseBody
    public Map<String,Object> getCustomAlert(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            EntityPageBean<TtPackWeeklyReport> pageBean = this.ttPackWeeklyReportService.findEntityPageByQuery(map, pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }

    @RequestMapping(value = "/findAlertDetail.mvc")
    @ResponseBody
    public Map<String,Object> findAlertDetail(String packCode,String startDate,String endDate) throws ServiceException, DaoException {
        List<Map<String, Object>> list = this.ttPackWeeklyReportService.findAlertDetail(packCode,startDate,endDate);
        Map<String, Object> result = new HashMap<>();
        result.put("data",list);
        result.put("result",true);
        result.put("message","");
        return result;
    }

    @RequestMapping(value = "/export.mvc")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException, DaoException {
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        /*
         * 构建动态map,进行excel导出
         */
        String fileName = "周报";
        String title = "周报";
        List<ExcelExportEntity> entity = new ArrayList<>();
        //构造方法 列head   列对应字段名      列宽
        entity.add(new ExcelExportEntity("电池ID", "packCode", 20));
        entity.add(new ExcelExportEntity("采集终端ID", "colClientId", 20));
        entity.add(new ExcelExportEntity("电池型号", "packModel", 30));
        entity.add(new ExcelExportEntity("出厂日期", "productDateStr", 25));
        entity.add(new ExcelExportEntity("起始时间", "startDateStr", 15));
        entity.add(new ExcelExportEntity("结束时间", "endDateStr", 15));
        entity.add(new ExcelExportEntity("告警总次数", "alertCount", 25));
        entity.add(new ExcelExportEntity("告警详情", "alertData", 25));
        entity.add(new ExcelExportEntity("工作次数", "workCount", 25));
        entity.add(new ExcelExportEntity("工作时长（分钟）", "workTimeSpan", 25));
        entity.add(new ExcelExportEntity("放电电流最大值", "maxCurrentValue", 25));
        entity.add(new ExcelExportEntity("放电电流超过400A次数", "overproofCurrentCount", 25));
        entity.add(new ExcelExportEntity("充电次数", "chargeCount", 25));
        entity.add(new ExcelExportEntity("充电时长（分钟）", "chargeTimeSpan", 25));
        entity.add(new ExcelExportEntity("压差最大时间", "maxVolDiffDateStr", 25));
        entity.add(new ExcelExportEntity("压差最大值", "maxVolDiffValue", 25));
        entity.add(new ExcelExportEntity("温差最大时间", "maxTempDiffDateStr", 25));
        entity.add(new ExcelExportEntity("温差最大值", "maxTempDiffValue", 25));



        /*
         * 封装查询条件进map
         */
        List<Map<String, Object>> list = this.ttPackWeeklyReportService.findWeeklyReport(map);
        //调用导出方法进行excel导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
                title, title), entity, list);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        workbook.write(bao);
        RmsUtil.exportExcel(fileName.concat(".xls"), response, bao);
        bao.close();
    }
}
